package com.meilai.project.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author 张驰
 * @date 2020/12/16 16:00
 */
public class PinYinUtil {
    public static String getStringPinYin(String str, boolean ... hasOtherWord){
        StringBuilder sb = new StringBuilder();
        String tempPinyin = null;
        for(int i = 0; i < str.length(); ++i) {
            tempPinyin =getCharacterPinYin(str.charAt(i), false, true);
            if(tempPinyin == null) {
                // 如果str.charAt(i)非汉字，则保持原样
                if(hasOtherWord != null && hasOtherWord.length>0 && hasOtherWord[0]){
                    sb.append(str.charAt(i));
                }
            } else {
                sb.append(tempPinyin);
            }
        }
        return sb.toString();
    }

    private static String getCharacterPinYin(char c, boolean useUppercase, boolean firstChar){
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(useUppercase?HanyuPinyinCaseType.UPPERCASE:HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        String[] pinyin = null;
        try {
            pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
        } catch(BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return (pinyin==null || pinyin.length==0)?null:(firstChar?String.valueOf(pinyin[0].charAt(0)):pinyin[0]);
    }
}
